/*
 * Socket.h
 *
 *  Created on: 2012-10-15
 *      Author: tony
 */

#ifndef SOCKET_H_
#define SOCKET_H_

#define _WIN32_WINNT 0x501

#include <winsock2.h>
#include <ws2tcpip.h>

#include <string>
#include "CriticalSection.h"
#include "Thread.h"
#include "Win32.h"

using namespace std;

class SocketError
{
public:
	SocketError(int error)
		: m_error(error)
	{
		Win32::GetErrorString(error, m_error_string);
	};

	SocketError(const SocketError& socket_error)
	{
		*this=socket_error;
	}

	SocketError& operator=(const SocketError& socket_error)
	{
		this->m_error = socket_error.m_error;
		this->m_error_string = socket_error.m_error_string;
		return *this;
	}

	SocketError& operator=(const int error)
	{
		this->m_error = error;
		Win32::GetErrorString(error, m_error_string);
		return *this;
	}
	virtual ~SocketError(){};

	int GetError(){ return m_error;}
	string GetErrorString(){ return m_error_string; }


private:
	SocketError()
		: m_error(0)
		, m_error_string("")
	{};

	int m_error;
	string m_error_string;

};

class Socket : public IThread
{
public:
    Socket();
    virtual ~Socket();

    SocketError StartServer(const char* port);
    virtual void Run();

private:

    SOCKET m_listen_socket;

    static CriticalSection sm_criticalsection;
    static WSADATA	sm_wsa_data;
    static bool sm_is_wsa_started;
};

#endif /* SOCKET_H_ */
